<?php

/**
 * User:ayou chow
 * Date: 2020-02-06
 * Time: 11:28
 */

namespace app\admin\controller;


use app\common\model\NoticeModel;
use app\common\model\UserAuthModel;
use app\common\model\UserModel;
use app\service\UserService;
use think\Db;
use think\Exception;
use think\facade\Request;

class AuthController extends BaseController
{
    public function index()
    {
        return $this->fetch();
    }

    public function getlist()
    {
        $uid    = Request::param("uid");
        $status = Request::param("status");
        $where  = [];
        if ($uid) {
            $where['uid'] = $uid;
        }
        if ($status != '') {
            $where['status'] = $status;
        }
        $page  = Request::param("page");
        $limit = Request::param("limit");
        $auths = UserAuthModel::where($where)->with(['user'])->limit(($page - 1) * $limit, $limit)->order('submit_time', 'desc')->select();
        if (count($auths) > 0) {
            $imgDomain = getConfigPub()->img_upload_url;
            $count     = UserAuthModel::where($where)->count();
            foreach ($auths as $auth) {
                // $auth->id_card_url = str_replace("{img_domain}", $imgDomain, $auth->id_card_url);
                // $auth['id_card_url'] = $imgDomain . $auth->id_card_url;
                $imgs = explode(',', $auth['id_card_url']);
                if (count($imgs) > 1) {
                    for ($i = 0; $i < count($imgs); $i++) {
                        if (stripos($imgs[$i], 'http://') === false && stripos($imgs[$i], 'https://') === false) {
                            $imgs[$i] = $imgDomain . $imgs[$i];
                        }
                    }
                    $auth['id_card_url'] = implode(',', $imgs);
                } else {
                    if (stripos($imgs[0], 'http://') === false && stripos($imgs[0], 'https://') === false) {
                        $imgs[0] = $imgDomain . $imgs[0];
                    }
                    $auth['id_card_url'] = $imgs[0];
                }
            }
            return json(["code" => 0, "msg" => "", "data" => $auths, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function check()
    {
        $uid           = Request::param('uid');
        $status        = Request::param('status');
        $reject_reason = Request::param('reject_reason');
        $is_anchor     = $status == 1 ? 1 : 0;

        $auth = UserAuthModel::where('uid', $uid)->find();
        if (empty($auth)) {
            return self::bulidFail('认证信息不存在');
        }

        $user = UserModel::get($uid);
        if (empty($user)) {
            return self::bulidFail('用户信息不存在');
        }

        if ($auth->status == 1) {
            return self::bulidFail('认证信息已审核通过，不能操作');
        }

        $data   = [
            'status'        => $status,
            'reject_reason' => $reject_reason,
            'check_time'    => nowFormat()
        ];
        $u_data = [
            'is_anchor'     => $is_anchor,
            'anchor_type'   => $is_anchor ? 1 : 0,
            'sharing_ratio' => $is_anchor ? 40 : 0,
            'auth_time'     => date("Y-m-d H:i:s")
        ];

        Db::startTrans();
        try {
            if (!$auth->save($data)) {
                throw new \Exception('修改信息失败');
            }

            if (!$user->save($u_data)) {
                throw new \Exception('修改信息失败');
            }
            // 清理主播缓存
            UserModel::delAnchorCache();

            if ($status == 1) {
                $log_content = "设置通过主播({$uid})身份认证申请";
                $title       = '主播申请审核通过';
                $content     = "您的主播申请已审核通过，快去开启直播吧";

                // 设置es 主播数据
                $res = UserService::setAnchorEs($uid);
                if ($res['code'] != 0) {
                    throw new \Exception('修改信息失败');
                }

            } else {
                $log_content = "驳回主播({$uid})身份认证申请";
                $title       = '主播申请被驳回';
                $content     = "您的主播申请被驳回，驳回原因：{$reject_reason}";
            }

            // 记录日志
            parent::addAdminLog($log_content, $uid);
            // 用户通知
            $notice_model = new NoticeModel(['user_id' => $uid, 'title' => $title, 'content' => $content, 'create_time' => nowFormat()]);
            if (!$notice_model->save()) {
                throw new \Exception('通知添加失败');
            }

            Db::commit();
            return self::bulidSuccess();
        } catch (\Exception $e) {
            Db::rollback();
        }
        return self::bulidFail();
    }
}
